<template>
  <div class="container">
    <!-- 通知面板 -->
    <div class="notification-panel">
      <h4>通知</h4>
      <div v-if="notifications.length === 0" class="no-notifications">
        暂无通知
      </div>
      <transition-group name="slide">
        <div 
          v-for="notification in notifications"
          :key="notification.id"
          class="notification-item"
        >
          <img :src="notification.userPic || avatar" alt="Avatar" class="notification-avatar" />
          <div class="notification-content">
            <span class="username">{{ notification.username }}</span>
            {{ notification.message }}
          </div>
          <button @click="handleNotification(notification)">处理</button>
        </div>
      </transition-group>
    </div>
  
    <!-- 搜索和添加好友 -->
    <div class="search-container">
      <el-input 
        v-model="searchUsername"
        placeholder="输入用户名搜索"
        @keyup.enter="searchUser" 
      />
      <el-button @click="searchUser">搜索</el-button>
    </div>
  
    <!-- 搜索结果 -->
    <div v-if="searchResult" class="search-result">
      <img :src="searchResult.userPic || avatar" alt="Avatar" class="search-avatar" />
      <p>{{ searchResult.username }}</p>
      <el-button 
        @click="sendFriendRequest"
        :disabled="isFriend"
      >
        {{ isFriend ? "已是好友" : "添加好友" }}
      </el-button>
    </div>
  
    <!-- 好友列表 -->
    <h3>好友列表</h3>
    <el-table :data="friendList">
      <el-table-column prop="username" label="用户名" />
      <el-table-column>
        <template #default="{ row }">
          <img :src="row.userPic || avatar" alt="Avatar" class="friend-avatar" />
          <el-button @click="removeFriend(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import {
  searchUserByUsername,
  addFriend,
  getFriendList,
  deleteFriend,
  acceptFriendRequest,
  rejectFriendRequest,
  getNotifications,
} from "@/api/friend";
import { connectWebSocket, addNotificationListener } from "@/utils/websocket";
import { userInfoService } from "@/api/user";
import useUserInfoStore from "@/stores/userInfo";
import avatar from '@/assets/default.png'
import { ElMessage, ElMessageBox } from 'element-plus'

// 状态变量
const searchUsername = ref("");
const searchResult = ref(null);
const friendList = ref([]);
const notifications = ref([]);
const userInfoStore = useUserInfoStore();

// 计算属性：检查是否已经是好友
const isFriend = computed(() => {
  if (!searchResult.value) return false;
  return friendList.value.some(friend => friend.id === searchResult.value.id);
});

// 加载历史通知
const loadHistoryNotifications = async () => {
  try {
    const userId = userInfoStore.info.id;
    const { data } = await getNotifications(userId);
    if (data) {
      // 确保为每个通知获取发送者信息
      const notificationsWithSenderInfo = await Promise.all(
        data.map(async (notification) => {
          try {
            const { data: senderInfo } = await userInfoService(notification.userId);
            return {
              id: notification.id,
              senderId: notification.userId,
              username: senderInfo.username,
              userPic: senderInfo.userPic,
              message: notification.message,
              status: notification.status,
              isRead: notification.isRead,
              createTime: notification.createTime
            };
          } catch (error) {
            console.error("获取发送者信息失败：", error);
            return {
              id: notification.id,
              senderId: notification.userId,
              username: "未知用户",
              userPic: avatar,
              message: notification.message,
              status: notification.status,
              isRead: notification.isRead,
              createTime: notification.createTime
            };
          }
        })
      );
      notifications.value = notificationsWithSenderInfo;
    }
  } catch (error) {
    console.error("加载历史通知失败：", error);
    ElMessage.error("加载通知失败");
  }
};

// 生命周期函数
onMounted(async () => {
  try {
    await Promise.all([
      loadFriends(),
      loadHistoryNotifications()
    ]);
    
    const userId = userInfoStore.info.id;
    connectWebSocket(userId);

    // 添加通知监听
    addNotificationListener(async (notification) => {
      try {
        if (notification.type === 'text') {
          const userIdMatch = notification.message.match(/用户 (\d+)/);
          if (userIdMatch) {
            const senderId = parseInt(userIdMatch[1]);
            const existingNotification = notifications.value.find(
              n => n.senderId === senderId && n.status === 0
            );
            
            if (!existingNotification) {
              const { data: senderInfo } = await userInfoService(senderId);
              notifications.value.unshift({
                id: Date.now(), // 生成临时ID
                senderId: senderId,
                username: senderInfo.username,
                userPic: senderInfo.userPic,
                message: `${senderInfo.username} 向您发送了好友请求`,
                status: 0,
                isRead: false,
                createTime: new Date().toISOString()
              });
            }
          }
        } else {
          // 处理JSON格式的通知
          const { data: senderInfo } = await userInfoService(notification.senderId);
          notifications.value.unshift({
            id: Date.now(), // 生成临时ID
            senderId: notification.senderId,
            username: senderInfo.username,
            userPic: senderInfo.userPic,
            message: notification.message,
            status: 0,
            isRead: false,
            createTime: new Date().toISOString()
          });
        }
      } catch (error) {
        console.error("获取发送者信息失败：", error);
        notifications.value.unshift({
          ...notification,
          username: "未知用户",
          userPic: avatar
        });
      }
    });
  } catch (error) {
    console.error("初始化失败：", error);
    ElMessage.error("加载数据失败");
  }
});

// 搜索用户
const searchUser = async () => {
  if (!searchUsername.value.trim()) {
    ElMessage.warning("请输入用户名");
    return;
  }
  
  try {
    const { data } = await searchUserByUsername(searchUsername.value);
    if (data) {
      searchResult.value = data;
    } else {
      ElMessage.warning("未找到该用户");
      searchResult.value = null;
    }
  } catch (error) {
    console.error("搜索用户失败：", error);
    ElMessage.error("搜索失败");
  }
};

// 发送好友请求
const sendFriendRequest = async () => {
  try {
    const userId = userInfoStore.info.id;
    await addFriend(userId, searchResult.value.id);
    ElMessage.success("好友请求已发送");
    searchResult.value = null;
    searchUsername.value = "";
  } catch (error) {
    console.error("发送好友请求失败：", error);
    ElMessage.error("发送请求失败");
  }
};

// 加载好友列表
const loadFriends = async () => {
  try {
    const userId = userInfoStore.info.id;
    const { data } = await getFriendList(userId);
    friendList.value = data || [];
  } catch (error) {
    console.error("加载好友列表失败：", error);
    ElMessage.error("加载好友列表失败");
  }
};

// 删除好友
const removeFriend = async (friendId) => {
  try {
    if (window.confirm("确定要删除这个好友吗？")) {
      const userId = userInfoStore.info.id;
      await deleteFriend(userId, friendId);
      ElMessage.success("好友已删除");
      await loadFriends();
    }
  } catch (error) {
    console.error("删除好友失败：", error);
    ElMessage.error("删除失败");
  }
};

// 处理通知
const handleNotification = async (notification) => {
  try {
    const userId = userInfoStore.info.id;
    const senderId = notification.senderId;
    
    // 使用 Element Plus 的确认对话框
    ElMessageBox.confirm(
      `${notification.username} 向您发送了好友请求，是否接受？`,
      '好友请求',
      {
        confirmButtonText: '接受',
        cancelButtonText: '拒绝',
        type: 'info'
      }
    ).then(async () => {
      // 接受好友请求
      await acceptFriendRequest(userId, senderId);
      ElMessage.success("已接受好友请求");
      
      // 从通知列表中移除该通知
      notifications.value = notifications.value.filter(
        n => !(n.senderId === senderId && n.status === 0)
      );
      
      // 刷新好友列表
      await loadFriends();
    }).catch(async () => {
      // 拒绝好友请求
      await rejectFriendRequest(userId, senderId);
      ElMessage.success("已拒绝好友请求");
      
      // 从通知列表中移除该通知
      notifications.value = notifications.value.filter(
        n => !(n.senderId === senderId && n.status === 0)
      );
    });
  } catch (error) {
    console.error("处理好友请求失败：", error);
    ElMessage.error("处理请求失败");
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.notification-panel {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  min-height: 100px;
}

.notification-panel h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.no-notifications {
  text-align: center;
  color: #909399;
  padding: 20px;
  font-size: 14px;
}

.notification-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.notification-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.notification-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.notification-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.notification-content .username {
  font-weight: bold;
  color: #409eff;
  margin-bottom: 4px;
}

.notification-item button {
  margin-left: 12px;
  padding: 6px 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.notification-item button:hover {
  background-color: #66b1ff;
}

.notification-item button:active {
  background-color: #3a8ee6;
}

.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-result {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.search-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.friend-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter-from,
.slide-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
